package com.bjpowernode.core;

import com.bjpowernode.constant.Constant;
import com.bjpowernode.util.HttpUtils;
import com.bjpowernode.util.LogUtils;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * Created whit IntelliJ IDEA.
 * Description：
 * User：ZHONGCHEN
 * Date:2022-10-28
 * Time:21:06
 */
public class DownLoaderTask implements Callable<Boolean> {
    private String url;

    private long startPos;

    private long endPos;

    //标识当前是那一部分
    private int part;

    private CountDownLatch countDownLatch;

    public DownLoaderTask(String url, long startPos, long endPos, int part, CountDownLatch countDownLatch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public Boolean call() throws Exception {
        //获取文件名
        String httpFileName = HttpUtils.getHttpFileName(url);
        //分块的文件名
        httpFileName = httpFileName + ".temp" + part;
        //下载到什么路径
        httpFileName = Constant.PATH + httpFileName;
        //获取分区下载的链接
        HttpURLConnection httpURLConner = HttpUtils.getHttpURLConner(url, startPos, endPos);

        try (BufferedInputStream bufferedInputStream =
                     new BufferedInputStream(httpURLConner.getInputStream());
             RandomAccessFile accessFile = new RandomAccessFile(httpFileName, "rw")
        ) {
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len = -1;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                //一秒内下载数据之和
                DownLoadInfo.downSize.add(len);
                accessFile.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            LogUtils.error("文件的文件不存在");
            return false;
        } catch (Exception e) {
            LogUtils.error("下载出现异常" + e.getMessage());
            System.out.println(e.fillInStackTrace());
            return false;
        } finally {
            countDownLatch.countDown();
            httpURLConner.disconnect();
        }

        return true;
    }
}
